package com.zhufeng.web.socket;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import io.netty.util.concurrent.GlobalEventExecutor;

import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @ClassName: ChatHandler
 * @Description TODO
 * @author 月夜烛峰
 * @date 2022/9/23 16:54
 */
public class MyScocketHandler extends SimpleChannelInboundHandler<TextWebSocketFrame> {

    /**用来保存所有的客户端连接*/
    public static ChannelGroup clients = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);
    /**时间格式化*/
    private SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    /**
     * 当有新的客户端连接服务器之后，会自动调用这个方法
     * @param ctx
     * @throws Exception
     */
    @Override
    public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
        // 将新的通道加入到clients
        clients.add(ctx.channel());
    }

    @Override
    protected void messageReceived(ChannelHandlerContext channelHandlerContext, TextWebSocketFrame msg) throws Exception {
        StringBuilder resMsg = new StringBuilder();
        // 获取客户端发送过来的文本消息
        String text = msg.text();
        System.out.println("获取客户端发送内容:" + text);
        //发送所有客户端
        /**
        for (Channel client : clients) {
            System.out.println("获取客户端:" + client.id());
            // 将消息发送到所有的客户端
         resMsg.append(text).append(",").append(channelHandlerContext.channel().id()).append(",").append(sdf.format(new Date()));
            client.writeAndFlush(new TextWebSocketFrame(resMsg.toString()));
        }
         */
        //发送指定客户端
        resMsg.append(text).append(",").append(channelHandlerContext.channel().id()).append(",").append(sdf.format(new Date()));
        channelHandlerContext.channel().writeAndFlush(new TextWebSocketFrame(resMsg.toString()));

    }
}

